﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxChatWebApp.DTO;

namespace AjaxChatWebApp
{
    public partial class SiteMaster : MasterPage
    {
        private const string AntiXsrfTokenKey = "__AntiXsrfToken";
        private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
        private string _antiXsrfTokenValue;

        protected void Page_Init(object sender, EventArgs e)
        {
            // The code below helps to protect against XSRF attacks
            var requestCookie = Request.Cookies[AntiXsrfTokenKey];
            Guid requestCookieGuidValue;
            if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
            {
                // Use the Anti-XSRF token from the cookie
                _antiXsrfTokenValue = requestCookie.Value;
                Page.ViewStateUserKey = _antiXsrfTokenValue;
            }
            else
            {
                // Generate a new Anti-XSRF token and save to the cookie
                _antiXsrfTokenValue = Guid.NewGuid().ToString("N");
                Page.ViewStateUserKey = _antiXsrfTokenValue;

                var responseCookie = new HttpCookie(AntiXsrfTokenKey)
                {
                    HttpOnly = true,
                    Value = _antiXsrfTokenValue
                };
                if (FormsAuthentication.RequireSSL && Request.IsSecureConnection)
                {
                    responseCookie.Secure = true;
                }
                Response.Cookies.Set(responseCookie);
            }

            Page.PreLoad += master_Page_PreLoad;
        }

        protected void master_Page_PreLoad(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // Set Anti-XSRF token
                ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
                ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;
            }
            else
            {
                // Validate the Anti-XSRF token
                if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue
                    || (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))
                {
                    throw new InvalidOperationException("Validation of Anti-XSRF token failed.");
                }
            }
        }

        HttpClient httpClient = new HttpClient();
        protected void Page_Load(object sender, EventArgs e)
        {
            httpClient.BaseAddress = new Uri("http://localhost:62865");
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            if(Session["IsLogin"] == null || (bool)Session["IsLogin"] == false)
            {
                SetLogin(true);
            }
            else
            {
                var user = GetUser((int)Session["UserId"]);
                if (user != null)
                {
                    imgAvatar.ImageUrl = "~/Avatars/" + user.Avatar;
                }
                SetLogin(false);
            }            
        }

        private void SetLogin(bool flag)
        {
            if(flag)
            {
                pnLogin.Visible = true;
                pnLogout.Visible = false;
            }
            else
            {
                lnkUserName.Text = Session["UserName"].ToString();
                pnLogin.Visible = false;
                pnLogout.Visible = true;
            }
        }

        protected void lnkLogout_Click(object sender, EventArgs e)
        {
            var user = GetUser((int)Session["UserId"]);
            if (user != null)
            {
                user.Status = false;
                Session["IsLogin"] = false;
                Session["UserId"] = -1;
                Session["UserName"] = "";
                UpdateUser(user);
            }

            Response.Redirect("~/Default.aspx");
            //SetLogin(true);
        }

        private User GetUser(int userId)
        {
            User user = null;
            HttpResponseMessage response = httpClient.GetAsync("api/users/" + userId).Result;
            if (response.IsSuccessStatusCode)
            {
                user = response.Content.ReadAsAsync<User>().Result;
            }
            return user;
        }

        private void UpdateUser(User user)
        {
            HttpResponseMessage response = httpClient.PutAsJsonAsync("api/users/" + user.Id, user).Result;
            if (response.IsSuccessStatusCode)
            {
                Response.Redirect("~/Default.aspx");
            }
        }
    }
}